import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { CreateUserDto } from '../users/dto/create-user.dto';
import { LoginUserDto } from '../users/dto/login-user.dto';
import { User } from '../users/schemas/user.schema';

@Injectable()
export class AuthService {
    constructor(
        private usersService: UsersService,
        private jwtService: JwtService,
    ) { }

    // 用户注册
    async register(createUserDto: CreateUserDto): Promise<User> {
        return this.usersService.create(createUserDto);
    }

    // 用户登录
    async login(loginUserDto: LoginUserDto): Promise<{ token: string; user: User }> {
        return this.usersService.login(loginUserDto);
    }

    // 发送短信验证码
    async sendSmsCode(phone: string): Promise<boolean> {
        return this.usersService.sendSmsCode(phone);
    }

    // 获取微信登录URL
    getWechatLoginUrl(): string {
        const appId = process.env.WECHAT_APP_ID || 'your_app_id';
        const redirectUri = encodeURIComponent(process.env.WECHAT_REDIRECT_URI || 'http://localhost:3000/api/auth/wechat-callback');
        const scope = 'snsapi_userinfo';
        const state = Math.random().toString(36).substring(2, 15);

        return `https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
    }

    // 微信回调处理
    async wechatCallback(code: string): Promise<{ token: string; user: User }> {
        const loginDto: LoginUserDto = {
            wechat_code: code,
            login_type: 'wechat'
        };

        return this.usersService.login(loginDto);
    }

    // 验证用户
    async validateUser(userId: string): Promise<User> {
        return this.usersService.findById(userId);
    }

    // 验证令牌
    validateToken(token: string): any {
        try {
            return this.jwtService.verify(token);
        } catch (e) {
            return null;
        }
    }
} 